package com.lwc.backendsinglestructure.strategy.sendStrategy;

import cn.hutool.core.util.StrUtil;
import com.lwc.backendsinglestructure.domain.dto.user.CaptchasForm;
import com.lwc.backendsinglestructure.exception.BusinessException;
import com.lwc.backendsinglestructure.exception.ErrorCode;
import com.lwc.backendsinglestructure.service.MailService;
import com.lwc.backendsinglestructure.strategy.SendHandler;
import com.lwc.backendsinglestructure.utils.CaptchaUtil;
import com.lwc.backendsinglestructure.utils.cache.CacheUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 邮箱发送验证码
 */
@Component("EMAIL_SEND")
@Slf4j
public class EmailSendStrategy implements SendHandler {

    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private MailService mailService;


    @Override
    public Boolean sendCaptcha(CaptchasForm captchasForm) {
        // 1.先校验是否重复发送
        String existCaptcha = cacheUtil.get("captcha:" +captchasForm.getBusiness() + ":" + captchasForm.getEmail());
        if(StrUtil.isNotBlank(existCaptcha)){
            throw new BusinessException(ErrorCode.REPEAT_CAPTCHA_ERROR);
        }
        // 2.校验邮箱是否为空 TODO 格式错误校验
        if(StrUtil.isBlank(captchasForm.getEmail())){
            throw new BusinessException(ErrorCode.EMAIL_ERROR);
        }
        // 3.拼接出验证码
        String captcha = CaptchaUtil.generateEmailCaptcha();
        log.info("验证码：" + captcha);

        try {
            // 4.调用api发送验证码
            mailService.sendTemplateMail(captchasForm.getEmail(), "测试验证码", "captcha", captcha);
            // 5。写入redis中记录 / 一分钟有效
            cacheUtil.set("captcha:" + captchasForm.getBusiness() + ":"+ captchasForm.getEmail(), captcha, 300);
            return true;
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.SEND_CAPTCHA_ERROR);
        }


    }
}
